//
//  ReplySubTableViewCell.swift
//  Gaoloumi
//
//  Created by Jasper on 4/4/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import AVOSCloud

class ReplySubTableViewCell: UITableViewCell, SDPhotoBrowserDelegate {
    
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var louIconWidth: NSLayoutConstraint! // 楼主标识
    @IBOutlet weak var userNameButton: UIButton!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var imageView1: UIImageView!
    @IBOutlet weak var imageView2: UIImageView!
    @IBOutlet weak var imageView3: UIImageView!
    @IBOutlet weak var updateTimeLabel: UILabel!
    @IBOutlet weak var imageHeight: NSLayoutConstraint!
    @IBOutlet weak var louLabel: UILabel! //  几楼
    @IBOutlet weak var louIconLabel: UILabel! //  楼标识
    
    
    @IBOutlet weak var subLouIconWidth: NSLayoutConstraint!
    @IBOutlet weak var subUserNameButton: UIButton!
    @IBOutlet weak var subContentLabel: UILabel!
    @IBOutlet weak var subUpdateTimeLabel: UILabel!
    @IBOutlet weak var louIconLabelText: UILabel!
    @IBOutlet weak var viewtoBottomHeight: NSLayoutConstraint!
    @IBOutlet weak var replyView: UIView!
    
    weak var delegate: ReplySubTableViewCellDelegate?
    
    var cellReply: Reply?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        louIconLabel.layer.cornerRadius = 2
        louIconLabel.layer.masksToBounds = true
        
        userImageView.layer.cornerRadius = 3
        userImageView.layer.masksToBounds = true
        
        louIconLabelText.layer.cornerRadius = 2
        louIconLabelText.layer.masksToBounds = true
        
        replyView.layer.cornerRadius = 4
        replyView.layer.masksToBounds = true
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(ReplySubTableViewCell.tapGesture(_:)))
        imageView1.addGestureRecognizer(tap)
        let tap2 = UITapGestureRecognizer(target: self, action: #selector(ReplySubTableViewCell.tapGesture(_:)))
        imageView2.addGestureRecognizer(tap2)
        let tap3 = UITapGestureRecognizer(target: self, action: #selector(ReplySubTableViewCell.tapGesture(_:)))
        imageView3.addGestureRecognizer(tap3)
    }
    
    func refreshView(_ reply: Reply,topic: Topic, lou: Int) {
        cellReply = reply
        
        if topic.user == reply.user {
            louIconWidth.constant = 16
        } else {
            louIconWidth.constant = 0
        }
        if lou == 0 {
            louLabel.text = "沙发"
        } else if lou == 1 {
            louLabel.text = "板凳"
        } else {
            louLabel.text = "\(lou+1)楼"
        }
        
        userNameButton.setTitle(reply.user?.username, for: .normal)
        contentLabel.text = reply.content
        let imgFile = reply.user!.object(forKey: "avatar") as? AVFile
        if imgFile != nil {
            
            let url = URL(string: (imgFile?.url)!)
            
            userImageView.kf.setImage(with: url,
                                      placeholder: DataCenter.sharedInstance.placeholderImage,
                                      options: nil,
                                      progressBlock: { receivedSize, totalSize in
                                        
                },
                                      completionHandler: { image, error, cacheType, imageURL in
                                        
            })
        } else {
            userImageView.image = UIImage(named: "defaultUser")
        }
        
        let date = reply.object(forKey: "updatedAt") as! Date
        updateTimeLabel.text = DataCenter.sharedInstance.friendlyTime(date)
        
        var imgArray = [imageView1, imageView2, imageView3]
        var i = 0
        if reply.contentImage == nil || reply.contentImage?.count == 0 {
            imageHeight.constant = 0
        } else {
            let width = (UIScreen.main.bounds.width-8*4)/3
            let intWidth = Int(width)*2
            imageHeight.constant = width
            for image in reply.contentImage! {
                let urlstr = image.url
                if urlstr != nil {
                    let urlCon = "\(urlstr)?imageView/1/w/\(intWidth)/h/\(intWidth)"
                    let imageView = imgArray[i]
                    let url = URL(string: urlCon)
                    
                    imageView?.kf.setImage(with: url,
                                           placeholder: DataCenter.sharedInstance.placeholderImage,
                                           options: nil,
                                           progressBlock: { receivedSize, totalSize in
                                            
                        },
                                           completionHandler: { image, error, cacheType, imageURL in
                                            
                    })
                    
                    i += 1
                    imageView?.isUserInteractionEnabled = true
                }
            }
        }
        
        imgArray.removeSubrange(Range(0..<i))
        for imageView in imgArray {
            imageView?.image = nil
            imageView?.isUserInteractionEnabled = false
        }
        
        if reply.reply != nil {
            subUserNameButton.setTitle(reply.reply?.userName, for: UIControlState())
            subContentLabel.text = reply.reply?.content
            let date = reply.reply?.object(forKey: "updatedAt") as! Date
            subUpdateTimeLabel.text = DataCenter.sharedInstance.friendlyTime(date)
            louIconLabelText.text = "楼"
            if topic.user == reply.reply?.user {
                subLouIconWidth.constant = 16
            } else {
                subLouIconWidth.constant = 0
            }
            replyView.isHidden = false
            viewtoBottomHeight.constant = 2
        } else {
            subUserNameButton.setTitle("", for: UIControlState())
            subContentLabel.text = nil
            subUpdateTimeLabel.text = nil
            louIconLabelText.text = ""
            replyView.isHidden = true
            viewtoBottomHeight.constant = -30
        }
    }
    
    @IBAction func replyButtonClicked(_ sender: UIButton) {
        delegate?.replySubTableViewCellReplyClick(tag)
    }
    
    
    func tapGesture(_ sender: UITapGestureRecognizer) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self.contentView
        browser.imageCount = (cellReply!.contentImage?.count)!
        browser.currentImageIndex = ((sender.view?.tag)!-100)
        browser.delegate = self
        browser.show()
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let img = self.contentView.viewWithTag(100+index) as! UIImageView
        return img.image
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let url = cellReply?.contentImage![index].url
        return URL(string: url!)
    }
}


protocol ReplySubTableViewCellDelegate: class {
    
    func replySubTableViewCellReplyClick(_ cellRow: Int)
    
}
